<template>
  <div v-loading="loading">
    <div class="performance">
      <e-container>
        <div style="margin:10px 0 0 0">
          <div class="per-title">文艺演出</div>
          <div class="per-title2">PERFORMANCE SHOWCASE</div>
          <el-card>
            <form action="javascript:;" @submit="searchSubmit" class="form-search">
              <table class="jd-search">
                <tbody>
                <tr>
                  <td>
                    <p class="search-radio">
                      <a href="javascript:;" @click="selectRadio('per_type', '')" :class="{ active: !search.per_type }">
                        全部
                      </a>
                      <a href="javascript:;" v-for="r in mapperformancetype5" @click="selectRadio('per_type', r.id)" :class="{ active: search.per_type == r.id }" v-text="r.type"></a>
                      <el-input class="info-search-input" type="text" style="width: 250px" v-model.trim="search.per_name" @keyup.enter.native="searchSubmit"  placeholder="请输入关键词"></el-input>

                      <el-button type="success" class="info-search-button"
                                 @click="searchSubmit" icon="el-icon-search">
                      </el-button>
                    </p>
                  </td>
                </tr>
                </tbody>
              </table>
            </form>
            <el-row :gutter="30" style="margin: -15px -175px 0px;padding: 10px 79px 0px 129px;">
              <el-col v-for="r in list" :md="7" :key="r.id" style="margin-bottom: 20px">
                <PerformanceCard
                    :title="r.perName"
                    :performer="r.performer"
                    :place="r.perPlace"
                    :image="r.perImage"
                    :description="getShortDescription(r.perDescription)"
                    :to="'/performanceInfodetail?id=' + r.id"
                />
              </el-col>
            </el-row>
            <div style="margin-top: 10px;text-align: center">
              <el-pagination @current-change="loadList" :current-page="page" :page-size="20" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"></el-pagination>
            </div>
          </el-card>
        </div>
      </e-container>
    </div>
  </div>
</template>

<style type="text/scss" scoped lang="scss">
.performance{
  .el-card.is-always-shadow {
    margin-top: -18px;
  }
  .form-search {
    margin-bottom: 20px;

    .jd-search {
      border-top: 0;
      border-left: 0;
      width: 100%;
      p {
        margin: -9px 0 10px;
      }

      td {
        border-right: 0;
        border-bottom: 3px solid #DEDEDE;
        padding: 10px;
      }

      .search-radio {
        a {
          display: inline-block;
          padding: 8px 10px;
          margin-right: 15px;
          border-radius: 5px;
        }

        a.active {
          background: #7fabbe;
          color: #ffffff;
        }
      }
    }

    .info-search-button {
      //margin-left: 40px;
      border-color: #7fabbe;
      background-color: #7fabbe;

    }

    .info-search-input {
      margin-left: 527px;
    }
  }

  .per-title {
    text-align: center;
    font-size: 25px;
    width: 100%;
  }
  .per-title2 {
    margin-bottom: 3%;
    color: #8c8c8c;
    text-align: center;
    font-size: 17px;
    width: 100%;
  }

  .info-header {
    text-align: center;
    background-color: #7fabbe;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px 8px 0 0;
  }

}
</style>

<script>
import api from '@/api';
import { extend } from '@/utils/extend';

export default {
  data() {
    return {
      loading: false,
      list: [],
      search: {
        per_name: '',
        per_type: '',
        performer: '',
        per_place: '',
      },
      page: 1,
      pagesize: 12,
      totalCount: 0,
      mapperformancetype5: [],
    }
  },

  watch: {
    'search.per_name': {
      handler(newVal) {
        console.log('搜索关键词变化:', newVal);
      }
    }
  },

  methods: {
    getShortDescription(description) {
      if (!description) return '';
      return description.length > 25 ? description.substring(0, 25) + '...' : description;
    },

    searchSubmit() {
      this.page = 1;
      this.loadList(1);
    },

    loadList(page) {
      // console.log("前端接收到的分类数据:", this.mapperformancetype5); 
      if (this.loading) return;
      
      this.loading = true;
      this.page = page;

      const filter = {
        ...this.search,
        page: page.toString(),
        pagesize: this.pagesize.toString()
      };

      this.saveFilterToCookie(filter);

      this.$post(api.performanceInfo.weblist, filter)
        .then(res => {
          this.loading = false;
          if (res.code == api.code.OK) {
            this.list = res.data.list || [];
            this.totalCount = res.data.totalCount || 0;
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(err => {
          this.loading = false;
          this.$message.error(err.message);
        });
    },

    selectRadio(target, name) {
      this.$set(this.search, target, name);
      this.searchSubmit();
    },

    saveFilterToCookie(filter) {
      const filterStr = JSON.stringify(filter);
      document.cookie = `performanceInfoFilter=${filterStr}; path=/; max-age=3600`;
    },

    getFilterFromCookie() {
      const name = "performanceInfoFilter=";
      const decodedCookie = decodeURIComponent(document.cookie);
      const cookies = decodedCookie.split(';');
      
      for (let cookie of cookies) {
        cookie = cookie.trim();
        if (cookie.indexOf(name) === 0) {
          try {
            return JSON.parse(cookie.substring(name.length));
          } catch (e) {
            console.error('Cookie parse error:', e);
            return null;
          }
        }
      }
      return null;
    },

    initializeFromRoute() {
      const query = this.$route.query;
      if (query.page) {
        this.page = parseInt(query.page) || 1;
      }
      if (query.pagesize) {
        this.pagesize = parseInt(query.pagesize) || 12;
      }
      
      // 合并路由查询参数到搜索条件
      const searchParams = { ...this.search };
      Object.keys(query).forEach(key => {
        if (key !== 'page' && key !== 'pagesize') {
          searchParams[key] = query[key];
        }
      });
      this.search = searchParams;
    }
  },

  created() {
    // 初始化路由参数
    this.initializeFromRoute();

    // 从 Cookie 中读取筛选条件
    const filter = this.getFilterFromCookie();
    if (filter) {
        this.search = { ...this.search, ...filter };
    }

    // 获取分类数据 - 使用原来的方式
    this.$post(api.performanceInfo.weblist, {
        action: "getTypes"
    }).then(res => {
        this.mapperformancetype5 = res.data.mapperformancetype5 || [];
    }).catch(err => {
        console.error('获取分类数据失败:', err);
        this.$message.error('获取分类数据失败');
    });

    // 初始化加载列表
    this.loadList(this.page);
},

  beforeRouteUpdate(to, from, next) {
    const search = { ...this.search };
    if (to.query.page) {
      this.page = parseInt(to.query.page);
    }
    if (to.query.pagesize) {
      this.pagesize = parseInt(to.query.pagesize);
    }
    Object.keys(to.query).forEach(key => {
      if (key !== 'page' && key !== 'pagesize') {
        search[key] = to.query[key];
      }
    });
    this.search = search;
    this.loadList(this.page);
    next();
  }
}
</script>
